package net.app.help.dialogs;

import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;

import net.app.help.R;
import net.app.help.adapters.AddContactsListViewAdapter;
import net.app.help.db.DatabaseAdapter;
import net.app.help.model.Contact;

import java.util.ArrayList;

/**
 * Created by Boogaboo on 9.1.2015.
 */
public class AddContactDialog extends DialogFragment {

	private Context c;

	private ListView contactList;
	private AddContactsListViewAdapter addContactsListViewAdapter;
	private Button confirm;
	private ArrayList<Contact> contacts, imContacts;

	private onConfirmInterface callback;

//	public AddContactDialog(ArrayList<Contact> contacts) {
//
//	}


	/**Reads contacts from phone and returns ArrayList<Contact>*/
	private ArrayList<Contact> readContactsFromPhone() {
		ArrayList<Contact> contacts = new ArrayList<Contact>();
		ContentResolver cr = getActivity().getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
				String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
				if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
					Cursor pCur = cr.query(
											ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
											null,
											ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
											new String[]{id}, null);
					while (pCur.moveToNext()) {
						String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						Contact c = new Contact();
						c.setId(Integer.parseInt(id));			//ID FROM PHONE -> TEMPORARY AND TO BE CHANGED AFTER INSERTION INTO DATABASE
						c.setName(name);
						c.setTel(phoneNo);
						contacts.add(c);
						Log.d("readContactsFromPhone","c="+c.toString());
					}
					pCur.close();
				}
			}
		}
		return contacts;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			callback = (onConfirmInterface) activity;
			c = activity;
			DatabaseAdapter da = new DatabaseAdapter(c);
			da.openToRead();
			imContacts = da.getAllContacts();
			da.close();
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnConfirmInterface.");
		}
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		Log.d("ADDCONTACTDIALOG onCreateDialog",".....");

		contacts = readContactsFromPhone();

		Log.d("AddContactDialog onCreateView","contacts.size="+contacts.size());
		for (int j=0; j < imContacts.size(); j++) {
			Log.d("Importan kontakt #j="+j,"!!!!!!!!!_"+imContacts.get(j).getName()+"_!!!!!!!!!!!!");
			for (int i=0; i < contacts.size(); i++) {
				Log.d("Kontakt v imeniku #i="+i,""+contacts.get(i).getName());
				if (imContacts.get(j).getName().equals(contacts.get(i).getName())) {
					String tel = imContacts.get(j).getTel();
					tel = tel.replaceAll("\\s","");
					Log.e("Skrajšana številka","iz telefona: "+contacts.get(i).getTel()+" || skrajšana iz app: "+tel+" || orig. iz app"+imContacts.get(j).getTel());
					if (tel.equals(contacts.get(i).getTel())) {
						//kontakt se ujema po imenu in tel, zato za izbrišem iz seznama kontaktov v telefonu, da se izognemu ponovnemu dodajanju
						Log.e("NAŠO UJEMANJE","BRIŠEM");
						contacts.remove(i);
//						i--;
						break;
					}
				}
			}
		}
		Log.d("AddContactDialog onCreateView","PO REDČENJU: contacts.size="+contacts.size());

		return super.onCreateDialog(savedInstanceState);
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_add_contact, container);

		contactList = (ListView) v.findViewById(R.id.frag_add_con_lv_contact_list);
		contactList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);

		addContactsListViewAdapter = new AddContactsListViewAdapter(contacts, v.getContext());
		contactList.setAdapter(addContactsListViewAdapter);

		confirm = (Button) v.findViewById(R.id.frag_add_con_b_add_contact);
		confirm.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				int stIzbranih = contactList.getCheckedItemCount();
				Log.d("AddContactDialog onCreateView onClick","stIzbranih="+stIzbranih);

//				IMPLEMENT SAVING ARRAYLIST OF CONTACTS TO RETURN
//				SparseBooleanArray checked = contactList.getCheckedItemPositions();
				boolean[] selected = addContactsListViewAdapter.obtainSelected();
				ArrayList<Contact> selectedContacts = new ArrayList<Contact>();
				for (int i=0; i<contacts.size(); i++) {
					Log.d("onCreateView","checked value at i:"+selected[i]);
					if (selected[i]) {
						selectedContacts.add(contacts.get(i));
					}
				}
				callback.onConfirmAddContacts(selectedContacts);
				dismiss();
			}
		});

		return v;
	}

	public interface onConfirmInterface {
		public void onConfirmAddContacts(ArrayList<Contact> selectedContacts);
		public void onCancelAddContacts();
	}

}
